package com.summer.user.center.service;

import com.summer.user.center.mapper.DepartmentMapper;
import com.summer.user.center.model.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author likun
 * 2018/5/22 11:16
 **/
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;

    @Override
    public Department findAllDepartmentTree() {
        List<Department> departmentList = departmentMapper.findAll();
        //组装数据
        Department root = null;
        for (Department department : departmentList) {
            if (department.getParentId() == -1) {
                root = department;
                break;
            }
        }
        if (root != null) {
            assemblyTree(root, departmentList);
        }
        return root;
    }

    /**
     * 组装成树形结构
     *
     * @param department
     * @param departmentList
     */
    private void assemblyTree(Department department, List<Department> departmentList) {
        for (Department dept : departmentList) {
            if (department.getId().equals(dept.getParentId())) {
                if (department.getChildren() == null) {
                    department.setChildren(new ArrayList<>());
                }
                department.getChildren().add(dept);
                assemblyTree(dept, departmentList);
            }
        }
    }

    @Override
    public boolean addDepartment(String name, Long parentId) {
        return departmentMapper.addDepartment(name, parentId) > 0;
    }

    @Override
    public boolean editDepartment(Long id, String name) {
        return departmentMapper.editDepartment(id, name) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDepartment(Long id) {
        departmentMapper.deleteDepartment(id);
        departmentMapper.deleteDepartmentUsers(id);
        return true;
    }
}
